// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// k [author] rhyme_lph
// l [email]  rhymelph@gmail.com
// F [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/http_service/http_setting_service.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';

class NumberFormatProvider extends BaseProvider {
  Map<String, String> formatMap = {};

  @override
  Future get dataFuture => null;

  @override
  void initState() {
    super.initState();
    formatMap.clear();
    Config.settingInfo.numberFormats.forEach((element) {
      formatMap['${element.type}'] = '${element.prefix}-${element.digit}';
    });
  }

  MapEntry<String, String> currentSelectMapEntry;

  void onChange(MapEntry<String, String> e) async {
    currentSelectMapEntry = e;
    await Routes.navigateTo(RouterGenProviders.numberFormatInfoPage, params: {
      'title': e.key,
      'value': e.value,
    });
    update();
    final number = Config.settingInfo.numberFormats.firstWhere(
        (element) => element.type == currentSelectMapEntry.key,
        orElse: () => null);
    if (number != null) {
      List<String> stringList = formatMap[currentSelectMapEntry.key].split('-');
      if (stringList.first != number.prefix ||
          stringList.last != number.digit) {
        bool isSuccess = false;
        await post(
            HttpSettingService.updatePreferenceNumber(
              number.id,
              prefix: stringList.first,
              digit: stringList.last,
            ),
            autoHandler: AutoHandler.Toast,
            loadingTip: S.current.loading, onSuccess: (result) {
          isSuccess = true;
        });
        if (isSuccess == true) {
          number.digit = stringList.last;
          number.prefix = stringList.first;
          await RProvider.myProvider.updateGlobalMap();
        } else {
          formatMap[currentSelectMapEntry.key] = currentSelectMapEntry.value;
        }
        update();
      }
    }
    currentSelectMapEntry = null;
  }

  void updateFromInput(String preview) {
    if (currentSelectMapEntry != null) {
      formatMap[currentSelectMapEntry.key] = preview;
      update();
    }
  }
}
